package cn.daniel.oss.service.impl;

import cn.daniel.commonutils.exceptionhandler.exception.MyException;
import cn.daniel.commonutils.result.ResultCode;
import cn.daniel.oss.config.OssConstantConfig;
import cn.daniel.oss.service.OssService;
import com.aliyun.oss.OSS;

import com.aliyun.oss.OSSClientBuilder;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadPhotoFile(MultipartFile multipartFile) {
        String endPoint= OssConstantConfig.END_POINT;
        String keyId=OssConstantConfig.KEY_ID;
        String keySecret=OssConstantConfig.KEY_SECRET;
        String bucketName=OssConstantConfig.BUCKET_NAME;

        OSS ossClient =  new OSSClientBuilder().build(endPoint, keyId, keySecret);

        try{
            InputStream inputStream = multipartFile.getInputStream();
            String fileName = multipartFile.getOriginalFilename();
            String uuid= UUID.randomUUID().toString();
            fileName=uuid+fileName;
            String[] s = new Date().toLocaleString().split(" ");
            String datePath=s[0];
            fileName=datePath+"/"+fileName;
            ossClient.putObject(bucketName,fileName,inputStream);
            ossClient.shutdown();

            String url=new StringBuilder("https://").append(bucketName).append(".")
                    .append(endPoint).append("/").append(fileName).toString();
            return url;
        }catch (Exception e){

            e.printStackTrace();
            MyException.setException(ResultCode.UPLOAD_FILE_ERROR);
        }


        return null;
    }
}
